<template>
	<el-dialog
		:align-center="true"
		v-model="dialogVisible"
		title="登录"
		width="350"
		h-430px
		:before-close="handleClose"
	>
		<el-form ref="loginFormRef" :model="loginForm" label-width="auto" label-position="left" :rules="loginRules">
			<el-form-item prop="username">
				<el-input v-model="loginForm.username" size="large" placeholder="用户名" />
			</el-form-item>
			<el-form-item prop="password">
				<el-input v-model="loginForm.password" size="large" type="password" show-password placeholder="密码" />
			</el-form-item>
			<el-form-item>
				<el-button class="w-100%" type="primary" size="large" @click="handleLoginSubmit">登录</el-button>
			</el-form-item>
		</el-form>
		<!-- <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="dialogVisible = false"> Confirm </el-button>
      </div>
    </template> -->
	</el-dialog>
</template>

<script setup lang="ts">
import { useUserStore } from "@/store";
import type { FormInstance } from "element-plus";
// 外部库和依赖
import { type LocationQuery } from "vue-router";

const loginForm = reactive({
	username: "",
	password: "",
});

const userStore = useUserStore();
// 登录表单ref
const loginFormRef = ref<FormInstance>();
const loginRules = computed(() => {
	return {
		username: [
			{
				required: true,
				trigger: "blur",
				message: "login.message.username.required",
			},
		],
		password: [
			{
				required: true,
				trigger: "blur",
				message: "login.message.password.required",
			},
			{
				min: 6,
				message: "login.message.password.min",
				trigger: "blur",
			},
		],
	};
});

const $router = useRouter();
const handleLoginSubmit = () => {
	loginFormRef.value?.validate((valid: boolean) => {
		if (valid) {
			userStore.login(loginForm).then((res) => {
				const { path, queryParams } = parseRedirect();
				$router.push({ path: path, query: queryParams });
			});
		}
	});
};

const dialogVisible = ref(false);
const handleClose = () => {
	dialogVisible.value = false;
	// ElMessage.success('关闭登录窗口')
};

const $route = useRoute();
/** 解析 redirect 字符串 为 path 和  queryParams */
function parseRedirect(): {
	path: string;
	queryParams: Record<string, string>;
} {
	const query: LocationQuery = $route.query;
	const redirect = (query.redirect as string) ?? "/";

	const url = new URL(redirect, window.location.origin);
	const path = url.pathname;
	const queryParams: Record<string, string> = {};

	url.searchParams.forEach((value, key) => {
		queryParams[key] = value;
	});

	return { path, queryParams };
}

defineExpose({
	dialogVisible,
});
</script>

<style scoped lang="scss"></style>
